package com.atguigu.flink.timer;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/2/1
 *
 *   定时器，会在指定的时间执行一段逻辑。
 *      使用：
 *              ①指定定时器，定闹钟
 *              ②指定触发后执行的逻辑，闹钟响了，做什么事
 *
 *        判断传感器的水位，如果vc > 30，指定5s后触发的定时器，如果vc<=10，就取消定时器。
 *
 *     -------
 *     UnsupportedOperationException: Setting timers is only supported on a keyed streams.
 *          keyBy之后才能指定定时器
 *
 *     ------
 *      每个key各有各的定时器，互不影响！
 */
public class Demo1_ProcessingTimer
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {
                       //定时器触发时指定逻辑
                       @Override
                       public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                           System.out.println("触发了:" + ctx.getCurrentKey() + "在" +timestamp+" 的定时器，预警...");

                       }

                       long time = 0l;
                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                           TimerService timerService = ctx.timerService();

                           if (value.getVc() > 30){
                               time = System.currentTimeMillis() + 10000;
                               //指定定时器
                               timerService.registerProcessingTimeTimer(time);
                               System.out.println(ctx.getCurrentKey()+"指定了定时器:"+time);
                           }else{
                               if (value.getVc() <= 10){
                                   //删除定时器
                                   timerService.deleteProcessingTimeTimer(time);
                                   System.out.println(ctx.getCurrentKey()+"删除了定时器:"+time);
                               }
                           }

                           out.collect(value.toString());
                       }
                   })
                   .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
    }
}
